package com.king.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.king.common.lang.Result;
import com.king.entity.MPost;
import com.king.vo.MPostVo;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@RequestMapping("/admin")
@Controller
public class AdminController extends BaseController {

    /**
     * @param id    博客id
     * @param rank  0取消，1设置
     * @param field delete删除，stick置顶，status加精
     * @return
     */
    @ResponseBody
    @PostMapping("/postSet")
    public Result postSet(Long id, Integer rank, String field) {
        MPost post = mPostService.getById(id);
        Assert.notNull(post, "该博客已被删除！");

        boolean isUpdate = true;
        switch (field) {
            case "stick":
                post.setLevel(rank);
                break;

            case "status":
                post.setRecommend(rank == 1);
                break;

            case "delete":
                mPostService.removeById(id);
                isUpdate = false;
                break;
        }

        if (isUpdate) {
            mPostService.updateById(post);
        }
        return Result.success();
    }

    /**
     * 管理员后台初始化es数据
     *
     * @return
     */
    @ResponseBody
    @PostMapping("/initESData")
    public Result initESData() {

        int size = 10000;
        Page page = new Page();
        page.setSize(size);
        long total = 0;
        for (int i = 1; i < 1000; i++) {
            page.setCurrent(i);
            IPage<MPostVo> pageData = mPostService.paging(page, null, null, null, null, null);
            total += searchService.initESData(pageData.getRecords());
            if (pageData.getRecords().size() < size) {
                break;//最后一页
            }
        }

        return Result.success("ES索引初始化成功，共" + total + "条记录！", null);
    }

}
